//
//  BarcodeReader.m
//  MyBarcodeStore
//
//  Created by Mac on 2010/5/17.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "BarcodeReader.h"
#import "Utils/THUIImageWithString.h"

#import "Decoder.h"
#import "ResultParser.h"
#import "ParsedResult.h"
#import "ResultAction.h"
#import "MyStoreParsedResult.h"
#import "DbObject.h"

#import "TwoDDecoderResult.h"

@implementation BarcodeReader;

@synthesize messageView;
@synthesize messageTextView;
@synthesize messageHelpButton;
@synthesize imageView;
@synthesize toolbar;

@synthesize decoder;
@synthesize result;
@synthesize actions;

@synthesize resultPointViews;

#define HELP_BUTTON_WIDTH (44.0)
#define HELP_BUTTON_HEIGHT (55.0)

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
	if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])
	{
		self.title = @"讀取物品";
		self.navigationItem.title = @"讀取物品";
		
		self.tabBarItem.image =
		[UIImage imageWithString:@"\u2707" // Unicode code for a check-mark.
							font:[UIFont systemFontOfSize:
								  [UIFont systemFontSize]]
							size:CGSizeMake(29, 29)];
		
		isPickerAnimated = YES;
		pickerController = [[UIImagePickerController alloc] init];
		pickerController.delegate = self;
		
		Decoder *d = [[Decoder alloc] init];
		self.decoder = d;
		d.delegate = self;
		[d release];
	}
	return self;
}

- (void)imagePickerController:(UIImagePickerController *)picker
		didFinishPickingImage:(UIImage *)image
				  editingInfo:(NSDictionary *)editingInfo
{
#ifdef DEBUG
    NSLog(@"Image picked.");
#endif
	UIImage *imageToDecode = image;
	CGSize size = [image size];
	CGRect cropRect = CGRectMake(0.0, 0.0, size.width, size.height);
	
#ifdef DEBUG
	NSLog(@"picked image size = (%f, %f)", size.width, size.height);
#endif
	NSString *systemVersion = [[UIDevice currentDevice] systemVersion];
	
	if (editingInfo) {
		UIImage *originalImage = [editingInfo objectForKey:UIImagePickerControllerOriginalImage];
		if (originalImage) {
#ifdef DEBUG
			NSLog(@"original image size = (%f, %f)", originalImage.size.width, originalImage.size.height);
#endif
			NSValue *cropRectValue = [editingInfo objectForKey:UIImagePickerControllerCropRect];
			if (cropRectValue) {
				cropRect = [cropRectValue CGRectValue];
#ifdef DEBUG
				NSLog(@"crop rect = (%f, %f) x (%f, %f)", CGRectGetMinX(cropRect), CGRectGetMinY(cropRect), CGRectGetWidth(cropRect), CGRectGetHeight(cropRect));
#endif
				if (([picker sourceType] == UIImagePickerControllerSourceTypeSavedPhotosAlbum) &&
					[@"2.1" isEqualToString:systemVersion]) {
					// adjust crop rect to work around bug in iPhone OS 2.1 when selecting from the photo roll
					cropRect.origin.x *= 2.5;
					cropRect.origin.y *= 2.5;
					cropRect.size.width *= 2.5;
					cropRect.size.height *= 2.5;
#ifdef DEBUG
					NSLog(@"2.1-adjusted crop rect = (%f, %f) x (%f, %f)", CGRectGetMinX(cropRect), CGRectGetMinY(cropRect), CGRectGetWidth(cropRect), CGRectGetHeight(cropRect));
#endif
				}
				
				imageToDecode = originalImage;
			}
		}
	}
	
	[self dismissModalViewControllerAnimated:isPickerAnimated];
	[imageToDecode retain];
	[self.decoder decodeImage:imageToDecode cropRect:cropRect];
	[imageToDecode release];
	//[self updateToolbar];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
	[self dismissModalViewControllerAnimated:isPickerAnimated];
}

// DecoderDelegate methods

- (void)decoder:(Decoder *)decoder willDecodeImage:(UIImage *)image usingSubset:(UIImage *)subset{
	//[self clearImageView];
	[self.imageView setImage:subset];
}

- (void)decoder:(Decoder *)decoder 
  decodingImage:(UIImage *)image 
    usingSubset:(UIImage *)subset
       progress:(NSString *)message {
	//[self clearImageView];
	[self.imageView setImage:subset];
}

- (void)presentResultForString:(NSString *)resultString {
	self.result = [ResultParser parsedResultForString:resultString];
	self.actions = self.result.actions;
#ifdef DEBUG
	NSLog(@"result has %d actions", actions ? 0 : actions.count);
#endif
	//[self updateToolbar];
} 

- (void)presentResultPoints:(NSArray *)resultPoints 
                   forImage:(UIImage *)image
                usingSubset:(UIImage *)subset {
	// simply add the points to the image view
	imageView.image = subset;
	for (NSValue *pointValue in resultPoints) {
		[imageView addResultPoint:[pointValue CGPointValue]];
	}
}

- (void)decoder:(Decoder *)decoder didDecodeImage:(UIImage *)image usingSubset:(UIImage *)subset withResult:(TwoDDecoderResult *)twoDResult {
	[self presentResultForString:twoDResult.text];
	
	[self presentResultPoints:twoDResult.points forImage:image usingSubset:subset];
	
	NSLog(@"name: %@\nprice: %@\norigin: %@",
		  ((MyStoreParsedResult *)self.result).name,
		  ((MyStoreParsedResult *)self.result).price,
		  ((MyStoreParsedResult *)self.result).origin
	);
	
	// save the scan to the shared database
	//[[Database sharedDatabase] addScanWithText:twoDResult.text];
	[[[DbObject alloc] init] insertItem:((MyStoreParsedResult *)self.result).sourceString];
	
	//[self performResultAction:self];
}

- (void)decoder:(Decoder *)decoder failedToDecodeImage:(UIImage *)image usingSubset:(UIImage *)subset reason:(NSString *)reason {
	//[self updateToolbar];
}


- (void)willAnimateFirstHalfOfRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
	[super willAnimateFirstHalfOfRotationToInterfaceOrientation:toInterfaceOrientation duration:duration];
	
	if (imageView.image) {
		/*
		 CGRect viewBounds = imageView.bounds;
		 CGSize imageSize = imageView.image.size;
		 float scale = fmin(viewBounds.size.width / imageSize.width,
		 viewBounds.size.height / imageSize.height);
		 float xOffset = (viewBounds.size.width - scale * imageSize.width) / 2.0;
		 float yOffset = (viewBounds.size.height - scale * imageSize.height) / 2.0;
		 */
		
		/*
		for (UIView *view in resultPointViews) {
			view.alpha = 0.0;
		}
		*/
	}  
}

- (void)willAnimateSecondHalfOfRotationFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation duration:(NSTimeInterval)duration {
	[super willAnimateSecondHalfOfRotationFromInterfaceOrientation:fromInterfaceOrientation duration:duration];
	
	if (imageView.image) {
		/*
		 CGRect viewBounds = imageView.bounds;
		 CGSize imageSize = imageView.image.size;
		 float scale = fmin(viewBounds.size.width / imageSize.width,
		 viewBounds.size.height / imageSize.height);
		 float xOffset = (viewBounds.size.width - scale * imageSize.width) / 2.0;
		 float yOffset = (viewBounds.size.height - scale * imageSize.height) / 2.0;
		 */
		
		/*
		for (UIView *view in resultPointViews) {
			view.alpha = 1.0;
		}
		*/
	}  
}

/*
- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    if (self = [super initWithStyle:style]) {
    }
    return self;
}
*/

/*
- (void)viewDidLoad {
    [super viewDidLoad];

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
*/

- (void)viewWillAppear:(BOOL)animated {
	const int sourceTypeLength = 2;
	UIImagePickerControllerSourceType sourceType[sourceTypeLength];
	int i;
	
	sourceType[0] = UIImagePickerControllerSourceTypeCamera;
	sourceType[1] = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
	
    [super viewWillAppear:animated];
#ifdef DEBUG
	NSLog(@"BarcodeReader will show.");
#endif
	for (i = 0; i < sourceTypeLength; ++i)
	{
		// No if/switch in AppDelegate now,
		// but it should occurs infinite loop, don't know why it does not happen.
		if ([UIImagePickerController isSourceTypeAvailable:sourceType[i]])
		{        
			pickerController.sourceType = sourceType[i];
			[self presentModalViewController:pickerController animated:isPickerAnimated];
			break;
		}
	}
}

/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
	[super viewDidDisappear:animated];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}

- (void)dealloc {
	[pickerController release];
	[imageView release];
    [super dealloc];
}

@end

